package com.A21.GuoSai.demo.atom_adjust.config;


import com.A21.GuoSai.demo.atom_adjust.mapper.AtomServiceMapper;
import com.A21.GuoSai.demo.atom_adjust.utils.AtomServiceUtils;
import com.A21.GuoSai.demo.service_entity.entity.atom.AtomServicePojo;
import io.camunda.zeebe.spring.client.ZeebeClientLifecycle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AtomConfiguration implements CommandLineRunner {

    @Autowired
    ZeebeClientLifecycle clientLifecycle;

    @Autowired
    AtomServiceMapper atomServiceMapper;


    /**
     * 获取全部的原子服务信息
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private List<AtomServicePojo> getAtomFromConfig() throws NoSuchFieldException, IllegalAccessException {
        List<Closeable> list=AtomServiceUtils.getJobWorkerImpl(clientLifecycle);
        List<AtomServicePojo> workList=list.stream().map(closeable -> {
            try {
                return AtomServiceUtils.castToAtomService(AtomServiceUtils.getWorkerValueFromJobWorker(closeable));
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());

        return workList;
    }


    /**
     * 将所有的原子服务信息导入数据库
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private void initialDataBase() throws NoSuchFieldException, IllegalAccessException {
        List<AtomServicePojo> list= getAtomFromConfig();
        List<String> methodInfo=atomServiceMapper.getAtomMethodInfo();
        //如果出现相同methodInfo的，及时更改信息
        list.forEach(
            atom->{ if(methodInfo.contains(atom.getMethodInfo())) atomServiceMapper.updateAtom(atom); }
        );
        List<String> nameList=atomServiceMapper.getAtomNames();
        //过滤掉数据库中已经存在的原子服务
        list=list.stream().filter(atom -> !nameList.contains(atom.getName())).collect(Collectors.toList());
        for(AtomServicePojo atomServicePojo : list){
            atomServicePojo.setCreatedDate(new Date());
            atomServicePojo.setAtomDesc("--"+atomServicePojo.getType()+"--");
            atomServiceMapper.insertAtomService(atomServicePojo);
        }
    }


    /**
     * CommandLine接口的run方法会自动在IOC容器对象注入完成
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        initialDataBase();
        log.info("A21国赛--原子服务--容器初始化完毕--原子服务AtomSerive注入数据库完成");
    }
}
